package com.zh.mediaservice.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zh.mediacommon.constant.MessageConstant;
import com.zh.mediacommon.constant.ReserveConstant;
import com.zh.mediacommon.ecxeption.NotFoundException;
import com.zh.mediacommon.util.HanLPUtil;
import com.zh.mediapojo.entity.Doctor;
import com.zh.mediapojo.vo.*;
import com.zh.mediaservice.mapper.DepartmentMapper;
import com.zh.mediaservice.mapper.DoctorMapper;
import com.zh.mediaservice.mapper.MessageMapper;
import com.zh.mediaservice.mapper.UserChatDoctorMapper;
import com.zh.mediaservice.service.ReserveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class ReserveServiceImpl implements ReserveService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private  DepartmentMapper departmentMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserChatDoctorMapper userChatDoctorMapper;
    @Override
    public ReserveVO checkIsCanReserve(Integer doctorId, String reserveTime) {
        String key="";
        String key2="";
        if(reserveTime.equals("上午")) {
            key = ReserveConstant.NOW_NUM_AM;
            key2= ReserveConstant.MAX_NUM_AM;
        }
        else {
            key = ReserveConstant.NOW_NUM_PM;
            key2= ReserveConstant.MAX_NUM_PM;
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        Integer maxNum = (Integer) hashOperations.get(doctorId.toString(), key2);
        Integer nowNum = (Integer) hashOperations.get(doctorId.toString(), key);
        if (nowNum < maxNum) {
            if(reserveTime.equals("上午"))
                return ReserveVO.builder()
                        .maxAmNum(maxNum)
                        .nowAmNum(nowNum)
                        .doctorId(doctorId)
                        .canReserve(true).build();
            else
                return ReserveVO.builder()
                        .maxPmNum(maxNum)
                        .nowPmNum(nowNum)
                        .doctorId(doctorId)
                        .canReserve(true).build();

        }
        else{
            if(reserveTime.equals("上午"))
                return ReserveVO.builder()
                        .maxAmNum(maxNum)
                        .doctorId(doctorId)
                        .nowAmNum(nowNum)
                        .canReserve(false).build();
            else
                return ReserveVO.builder()
                        .maxPmNum(maxNum)
                        .nowPmNum(nowNum)
                        .doctorId(doctorId)
                        .canReserve(false).build();
        }
    }

    @Override
    @Transactional
    public List<DoctorVO> getDoctorList(String description) {
        Map<String, List<String>> departmentKeywords= (Map<String, List<String>>) redisTemplate.opsForValue().get("department::key");
        if(departmentKeywords==null)
            departmentKeywords=new HashMap<>();
        Set<String> departments = HanLPUtil.recommendDepartments(description,departmentKeywords);
        log.info("departments {}", departments);
        if(departments.isEmpty())
            departments.add("全科");
        List<String> departmentList = new ArrayList<>();
       departments.stream().forEach(departmentList::add);
        List<DoctorVO> doctors= doctorMapper.selectDoctorByDepartmentName(departmentList);
        Set<Long> keys = redisTemplate.opsForHash().keys(ReserveConstant.DOCTOR_ONLINE);
        log.info("在线医生 {}", keys);
        Set<Integer> doctorIdList =new HashSet<>();
        keys.stream().forEach(o -> doctorIdList.add(Integer.parseInt(o.toString())));
        doctors.sort(Comparator.comparingInt(o -> doctorIdList.contains(o.getDoctorId()) ? 0 : 1));
        for (DoctorVO doctor : doctors) {
            if(doctorIdList.contains(doctor.getDoctorId())) {
                log.info("doctor 在线{} ",doctor );
                doctor.setOnline(true);
            }
            else {
                doctor.setOnline(false);
            }
        }
        return doctors.subList(0,doctors.size()>=100?100:doctors.size());
    }

    @Override
    public ChatPageVO getHistoryChat(Integer page, Integer pageSize, Integer userId, Integer doctorId) {
        PageHelper.startPage(page,pageSize);
        Page<ChatVO> page1 = messageMapper.getHistoryChat(userId,doctorId);
        return new ChatPageVO(page1.getTotal(),page1.getResult());
    }

    @Override
    public List<ChatDoctorVO> getChatedDoctor(Long uid) {
        List<Long> dids=userChatDoctorMapper.getDoctorIdListByUId(uid);
        if (dids==null || dids.isEmpty())
            return Collections.emptyList();
        List<ChatDoctorVO> doctorVOS=doctorMapper.getChatDoctor(dids);
        return doctorVOS;
    }
}
